package cjj;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet("/admin/changePassword")
public class AdminChangePasswordServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Integer adminId = (Integer) request.getSession().getAttribute("adminId");
        if (adminId == null) {
            response.sendRedirect("/admin/login");
            return;
        }

        String oldPassword = request.getParameter("oldPassword");
        String newPassword = request.getParameter("newPassword");

        try (Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/webproject_2025", "root", "root");
             PreparedStatement stmt = conn.prepareStatement("SELECT * FROM admin WHERE id = ? AND password = ?")) {
            stmt.setInt(1, adminId);
            stmt.setString(2, oldPassword);
            ResultSet rs = stmt.executeQuery();
            if (rs.next()) {
                // 原密码验证通过，更新密码
                try (PreparedStatement updateStmt = conn.prepareStatement("UPDATE admin SET password = ? WHERE id = ?")) {
                    updateStmt.setString(1, newPassword);
                    updateStmt.setInt(2, adminId);
                    updateStmt.executeUpdate();
                    response.getWriter().println("密码修改成功");
                }
            } else {
                // 原密码验证失败
                response.getWriter().println("原密码错误");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            response.getWriter().println("数据库错误");
        }
    }
}